package com.ichir.projects.uiframework.xml;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;

/**
 * 
 * @author mahieddine
 *
 */
public class XmlBeanHelper {
	
	/**
	 * 
	 * @param bean
	 * @return
	 */
	protected static Object getBean(XmlBean bean) {
		try {
			Object newInstance = Class.forName(bean.getClassname()).newInstance();
			initializeBean(newInstance, bean);
			return newInstance;
		} catch (ClassNotFoundException e) {
			throw new BeanNotFoundException();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 
	 * @param newInstance
	 * @param bean
	 */
	private static void initializeBean(Object newInstance, XmlBean bean) {
		if (bean.getProperties() == null || bean.getProperties().size() <= 0) {
			return;
		}
		try {
			for (XmlProperty property : bean.getProperties()) {
				if (property.getBean() != null) {
					BeanUtils.copyProperty(newInstance, property.getName(), getBean(property.getBean()));
				} else {
					BeanUtils.copyProperty(newInstance, property.getName(), property.getValue());
				}
			}
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e);
		}
	}
}
